<?php

class Shop
{
	protected $request;
	protected $for;
	protected $product;
	
	function __construct ($p_request = "", $p_maxResult = 5) {
		$this->request = $p_request;
		$this->nb_item = -1;
		
		$api_key    = 'AIzaSyDg_9ZW0b7AxDWzaD_6yQSAd_69yRRdTPM';
		$country    = 'FR';
		$q          = urlencode($this->request);
		$startIndex = 0;
		$maxResults = $p_maxResult;
		
		$uri        = 'https://www.googleapis.com/shopping/search/v1/public/products?thumbnails=110:*&key='.$api_key.'&country='.$country.'&q='.$q.'&startIndex='.$startIndex.'&maxResults='.$maxResults;

		$contents = file_get_contents($uri);
		$this->products = json_decode($contents);
		
		$total = $this->products->totalItems;
		
		$start = $this->products->startIndex;
		$end   = $start + $maxResults;
		 
		// Fin de liste ?
		if ($end > $total) {
		  $end = $total;
		  $this->for = $total - $start;
		}
		else {
		  $this->for = $maxResults;
		}
	}
	
	function getAt($index) {
		$items = $this->products->items[$index]->product;
		
		$arr  = array();
		
		$arr['title']       = $items->title;
		$arr['description'] = $items->description;
		$arr['link']        = $items->link;
		$arr['image']       = $items->images[0]->thumbnails[0]->link;
		$arr['brand']       = $items->brand;
		$arr['condition']   = $items->condition;
		$arr['author']      = $items->author->name;
		$arr['price']       = $items->inventories[0]->price;
		$arr['currency']    = $items->inventories[0]->currency;
		
		return $arr;
	}
	
	function fetchAll() {
		$arr  = array();
		
		for ($i = 0; $i < $this->for; $i++) {
			$arr[$i] = $this->getAt($i);
		}
		
		return $arr;
	}
}

?>